/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO.Financial;

import DAO.exceptions.IllegalOrphanException;
import DAO.exceptions.NonexistentEntityException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import FinancialEntity.Company;
import FinancialEntity.Market;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author Sebastian
 */
public class MarketDAO implements Serializable, DAOFinancial {

    public void create(Market market, EntityManager em) {
        if (market.getCompanyList() == null) {
            market.setCompanyList(new ArrayList<Company>());
        }
            List<Company> attachedCompanyList = new ArrayList<Company>();
            for (Company companyListCompanyToAttach : market.getCompanyList()) {
                companyListCompanyToAttach = em.getReference(companyListCompanyToAttach.getClass(), companyListCompanyToAttach.getId());
                attachedCompanyList.add(companyListCompanyToAttach);
            }
            market.setCompanyList(attachedCompanyList);
            em.persist(market);
            for (Company companyListCompany : market.getCompanyList()) {
                Market oldMarketidOfCompanyListCompany = companyListCompany.getMarketid();
                companyListCompany.setMarketid(market);
                companyListCompany = em.merge(companyListCompany);
                if (oldMarketidOfCompanyListCompany != null) {
                    oldMarketidOfCompanyListCompany.getCompanyList().remove(companyListCompany);
                    oldMarketidOfCompanyListCompany = em.merge(oldMarketidOfCompanyListCompany);
                }
            }
    }

    public void edit(Market market, EntityManager em) throws IllegalOrphanException, NonexistentEntityException, Exception {
        try {
            Market persistentMarket = em.find(Market.class, market.getId());
            List<Company> companyListOld = persistentMarket.getCompanyList();
            List<Company> companyListNew = market.getCompanyList();
            List<String> illegalOrphanMessages = null;
            for (Company companyListOldCompany : companyListOld) {
                if (!companyListNew.contains(companyListOldCompany)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Company " + companyListOldCompany + " since its marketid field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Company> attachedCompanyListNew = new ArrayList<Company>();
            for (Company companyListNewCompanyToAttach : companyListNew) {
                companyListNewCompanyToAttach = em.getReference(companyListNewCompanyToAttach.getClass(), companyListNewCompanyToAttach.getId());
                attachedCompanyListNew.add(companyListNewCompanyToAttach);
            }
            companyListNew = attachedCompanyListNew;
            market.setCompanyList(companyListNew);
            market = em.merge(market);
            for (Company companyListNewCompany : companyListNew) {
                if (!companyListOld.contains(companyListNewCompany)) {
                    Market oldMarketidOfCompanyListNewCompany = companyListNewCompany.getMarketid();
                    companyListNewCompany.setMarketid(market);
                    companyListNewCompany = em.merge(companyListNewCompany);
                    if (oldMarketidOfCompanyListNewCompany != null && !oldMarketidOfCompanyListNewCompany.equals(market)) {
                        oldMarketidOfCompanyListNewCompany.getCompanyList().remove(companyListNewCompany);
                        oldMarketidOfCompanyListNewCompany = em.merge(oldMarketidOfCompanyListNewCompany);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = market.getId();
                if (findMarket(id, em) == null) {
                    throw new NonexistentEntityException("The market with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } 
    }

    public void destroy(Integer id, EntityManager em) throws IllegalOrphanException, NonexistentEntityException {
            Market market;
            try {
                market = em.getReference(Market.class, id);
                market.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The market with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Company> companyListOrphanCheck = market.getCompanyList();
            for (Company companyListOrphanCheckCompany : companyListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Market (" + market + ") cannot be destroyed since the Company " + companyListOrphanCheckCompany + " in its companyList field has a non-nullable marketid field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(market);
    }

    public List<Market> findMarketEntities(EntityManager em) {
        return findMarketEntities(true, -1, -1, em);
    }

    public List<Market> findMarketEntities(int maxResults, int firstResult, EntityManager em) {
        return findMarketEntities(false, maxResults, firstResult, em);
    }

    private List<Market> findMarketEntities(boolean all, int maxResults, int firstResult, EntityManager em) {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Market.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
    }

    public Market findMarket(Integer id, EntityManager em) {
        return em.find(Market.class, id);
    }

    public int getMarketCount(EntityManager em) {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Market> rt = cq.from(Market.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        
    }
    
}
